<?php

if (!defined('IN_XLP')) {
	exit('Access Denied');
}

/**
 * Description of menuAction
 * 提现管理
 * @author skyinter
 */
class cashAction extends commonAction {

	function __construct() {
		parent::__construct();
        parent::_checkLogin();
  //       G('path_mod', 2);
        $orderStateArry = array(
				0 => '<span class="gray">已取消</span>',
				10 => '<span class="green">申请提现</span>',
				30 => '<span class="yellow">财务审核</span>',
				70 => '<span class="clre">提现完成</span>'
		);
		$this->assign('orderStateArry' , $orderStateArry);

	}

	function _empty() {
		return $this->index(); 
	}


	public function index() {
		$page		= empty($_GET['page']) ? 1 : intval($_GET['page']);
		$limit 		= ($page - 1)*20;
		$starttime  = empty($_GET['starttime']) ? null : $_GET['starttime'];
		$endtime    = empty($_GET['endtime']) ? null : $_GET['endtime'];
		$searchtype = isset($_GET['searchtype']) ? intval($_GET['searchtype']) : null;
		$keyword	= empty($_GET['keyword']) ? null : trim($_GET['keyword']);

		//goods order_goods order 表别名 g og o

		$where = ' is_del = 0 ';
		//订单状态
		if(isset($_GET['status'])) {
			$status = intval($_GET['status']);
			$where  = " c.`status`= $status ";
		} else {
			$status = '';
		}

		// 0-下单时间 1-支付时间 默认下单时间
		$timetype_code = isset($_GET['timetype']) ? intval($_GET['timetype']) : 0;
		switch ($timetype_code) {
			case 0:
				$timetype = 'o.`create_time`';
				break;
			case 1:
				$timetype = 'o.`confirm_time`';
				break;
			default:
				$timetype = 'c.`create_time`';
				break;
		}

		//起始时间
		if($starttime) $where .= " AND $timetype >= ".strtotime($starttime)." ";
		if($endtime)   $where .= " AND $timetype <= ".strtotime($endtime)." ";

		//搜索字段
		if($keyword) {
			switch ($searchtype) {
				case '1':
					$where .= " AND c.`order_sn` LIKE '%".$keyword."%' ";
					break;
				// case '2':
				// 	$where .= " AND u.`name` LIKE '%".$keyword."%' ";
				// 	break;
				case '3':
					$where .= " AND c.`phone` LIKE '%".$keyword."%' ";
					break;
				default:
					break;
			}
		}

		//查询20笔订单
		$sql = "SELECT c.`id`, c.`order_sn`, c.`uid`, c.`phone`, c.`amount`, c.`status`,c.`create_time`,c.`finish_time`, u.`name` FROM __PRE__cash_order c LEFT JOIN __PRE__user_detail u ON c.`uid` = u.`uid` WHERE {$where} ORDER BY c.`create_time` DESC";

		if(!isset($_GET['export'])) {
			$sql .= " LIMIT $limit,20";
		}

		$order_result = M()->query($sql);
		// z($order_result);
		
		//符合条件的全部订单数量
		$sql = "SELECT COUNT(`id`) AS total FROM __PRE__cash_order c WHERE $where";
		$total = M()->query($sql);
		$order_total = $total[0]['total'];


		//所有订单id
		$order_ids = '';
		foreach ($order_result as $v) {
			$order_ids .= $v['id'].',';
		}
		$order_ids = rtrim($order_ids, ',');
		if(empty($order_ids)) $order_ids = 0;

		//导出订单
		if(isset($_GET['export']) && $_GET['export']==1) {
			$this->export($order_result);
			exit;
		}
		//导出订单URL
		$url = parse_url(URL);
		if(isset($url['query']) && count($url['query'])) {
			$export_url = URL.'&export=1';
		} else {
			$export_url = URL.'?export=1';
		}
		$this->assign('export_url', $export_url);
		
		$url = preg_replace('/[&\?]status=\d*/', '', URL);
		if(strpos($url, '?') === false) {
			$this->assign('status_url', $url.'?status=');
		} else {
			$this->assign('status_url', $url.'&status=');
		}


		$this->assign('starttime', $starttime);
		$this->assign('endtime', $endtime);
		$this->assign('searchtype', $searchtype);
		$this->assign('keyword', $keyword);
		//下单时间or付款时间
		$this->assign('timetype', $timetype_code);
		//订单状态
		$this->assign('status', $status);
		//页码
		$this->assign('page', $page);
		//订单列表
		$this->assign('order_list', $order_result);
		//订单总数
		$this->assign('order_total', $order_total);
		$this->display();
	}




	/*
	 * 导出csv格式订单
	 */
	private function export($orders) {
		// z($orders);
		foreach ($orders as $k => $v) {
			switch ($orders[$k]['order_state']) {
				case 0:
					$orders[$k]['state'] = '已取消';
					break;
				case 10:
					$orders[$k]['state'] = '未支付';
					break;
				case 20:
				case 30:
					$orders[$k]['state'] = '已付款';
					break;
				case 40:
					$orders[$k]['state'] = '已发货';
					break;
				case 50:
					$orders[$k]['state'] = '已收货';
					break;
				case 60:
					$orders[$k]['state'] = '申请退款';
					break;
				case 61:
					$orders[$k]['state'] = '申请退货退款';
					break;
				case 70:
					$orders[$k]['state'] = '退款已处理';
					break;
				case 71:
					$orders[$k]['state'] = '退货退款已处理';
					break;
				default:
					$orders[$k]['state'] = 'unknown';
					break;
			}
			unset($orders[$k]['order_state_btn']);
		}

		// z($orders);
		
		$order_list  = array();
		$order_title = array('小区','昵称','订单号','商品','数量','收货人','电话','收货地址','状态','下单时间','支付时间');
		foreach ($orders as $k => $v) {
			//多商品
			$goods = '';
			$goods_num = 0;
			foreach ($v['order_goods'] as $value) {
				$goods = $value['goods_name'].' x '.$value['goods_num'].'件';
				if($value['spec_info']) $goods .= '('. json_decode($value['spec_info'], true) .')';
				$goods .= "  ";
				$goods_num += $value['goods_num'];
			}

			$order_list[] = array(
				'village'      => $v['village'],
				'nickname'     => $v['nickname'],
				'order_sn'     => "\t".$v['order_sn'],
				'goods'	       => $goods,
				'goods_num'    => $goods_num,
				'recipient'    => $v['recipients'],
				'phone'		   => "\t".$v['phone'],
				'address'	   => $v['address'],
				'state'		   => $v['state'],
				'create_time'  => "\t".date('Y-m-d H:i:s',$v['create_time']),
				'payment_time' => $v['payment_time'] ? "\t".date('Y-m-d H:i:s',$v['payment_time']) : '',
			);
		}

		load('csv');
		$csv = new csv();
		$csv->write($order_title, $order_list, "订单".date('Y-m-d'));
	}


	/*
	 * 发货表单
	 */
	public function deliver_form() {

		if(isset($_POST['order_id'])) {

			$order_id 			 = $this->_postid('order_id');
			$shipping_code 		 = $this->_post('shipping_code');
			$shipping_express_id = $this->_post('shipping_express_id');

			//发货
			$result = D('order')->deliver($order_id, $shipping_express_id, $shipping_code);

			if($result) {
				$this->JsonReturn('处理成功', null, 1);
			} else {
				$this->JsonReturn('处理失败', null, 0);
			}
		}

		//发货表单信息
		$express = D('express')->findAll();
		$this->assign('express', $express);

		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')->field('`id`,`order_sn`,`recipients`')->where(array('id'=>$order_id))->find();
		$order_goods = M('order_goods')->field('`goods_name`,`goods_num`')->where(array('order_id'=>$order_id))->findAll();

		$this->assign('order_goods', $order_goods);
		$this->assign('order', $order_info);
		$this->display();
	}

	/*
	 * 取消订单表单
	 */
	public function cancel_form() {

		if(isset($_POST['order_id'])) {
			$order_id = $this->_postid('order_id');
			$remark 	  = $this->_post('remark');
			//取消
			$result = D('order')->cancel($order_id, $remark);
			if($result) {
				$this->JsonReturn('取消成功', null, 1);
			} else {
				$this->JsonReturn('取消失败', null, 0);
			}
		}

		//取消订单表单信息
		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')->field('`id`,`order_sn`,`create_time`')->where(array('id'=>$order_id))->find();

		$this->assign('order', $order_info);
		$this->display();
	}

	/*
	 * 还款失败
	 */
	public function cancel_payment() {

		if(isset($_POST['order_id'])) {
			$order_id = $this->_postid('order_id');
			//取消
			$map['order_state'] = 61;
			$map['reason'] = $this->_post('reason');
			$result = M('order')->update($map , array('id' => $order_id));
			if($result) {
				$this->JsonReturn('操作成功', null, 1);
			} else {
				$this->JsonReturn('操作失败', null, 0);
			}
		}

		//取消订单表单信息
		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')->field('`id`,`order_sn`,`create_time`')->where(array('id'=>$order_id))->find();

		$this->assign('order', $order_info);
		$this->display();
	}

	/*
	 * 退款表单
	 */
	public function refund_form() {

		if(isset($_POST['order_id'])) {
			$order_id = $this->_postid('order_id');
			$agree 	  = $this->_postid('agree');
			$note	  = $this->_post('note');

			//客服处理退款
			$result = D('return')->service_refund($order_id, $agree, admin::$adminInfo['id'], $note);

			if($result) {
				$this->JsonReturn('处理成功', null, 1);
			} else {
				$this->JsonReturn('处理失败', null, 0);
			}
		}

		//退款订单表单信息
		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')
			->field('`id`,`order_sn`,`refund_time`,`refund_amount`,`recipients`')
			->where(array('id'=>$order_id))
			->find();

		//退款商品
		$refund_goods = M('order_goods')
			->field('`goods_name`,`goods_num`,`goods_refund`')
			->where("`order_id`={$order_info['id']} AND `goods_refund`>0")
			->findAll();

		//退款原因
		$refund = M('return_log')
			->field('`return_msg`')
			->where(array('order_id'=>$order_id))
			->find();

		$this->assign('order', $order_info);
		$this->assign('refund_goods', $refund_goods);
		$this->assign('refund_reason', $refund['return_msg']);
		$this->display();
	}

	/*
	 * 退货表单
	 */
	public function return_form() {

		if(isset($_POST['order_id'])) {
			$order_id = $this->_postid('order_id');
			$agree 	  = $this->_postid('agree');
			$note	  = $this->_post('note');
			
			//客服处理退货
			$result = D('return')->service_return($order_id, $agree, admin::$adminInfo['id'], $note);

			if($result) {
				$this->JsonReturn('处理成功', null, 1);
			} else {
				$this->JsonReturn('处理失败', null, 0);
			}
		}

		//退货订单表单信息
		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')
			->field('`id`,`order_sn`,`refund_time`,`refund_amount`,`return_amount`,`recipients`')
			->where(array('id'=>$order_id))
			->find();

		//退货商品
		$return_goods = M('order_goods')
			->field('`goods_name`,`goods_num`,`goods_returnnum`,`goods_refund`')
			->where("`order_id`={$order_info['id']} AND `goods_returnnum`>0")
			->findAll();

		//退货原因
		$refund = M('return_log')
			->field('`return_msg`')
			->where(array('order_id'=>$order_id))
			->find();

		$this->assign('order', $order_info);
		$this->assign('return_goods', $return_goods);
		$this->assign('return_reason', $refund['return_msg']);
		$this->display();
	}



	/**
	 * 订单详情
	 */
	public function info(){
		$id = $this->_get('id');
		if($id){
			$info 	= D('order')->info($id);
			//超出逾期，计算超出时间
			if($info['order_state'] == 62) {
				$due_time = $info['due_time'];
				$now_time = TIME;//TIME;
				$diff_days = round(($now_time - $due_time)/86400)+1;
				//计算超出逾期利息
				$setting = F('weixin/setting'); //获取利率配置
				$over_rate = $setting['basic_setting']['over_rate'];
				$over_interest = $info['amount'] * ($over_rate/100) * $diff_days;
				$this->assign(array('diff_days'=>$diff_days , 'over_interest' => $over_interest));
			}
			$info['name'] = D('member')->getUserRealName($info['user_id']);
			$data_list = M('order_interest')->where(array('order_id' => $id))->findAll();
			$lxStatusArray = array(
				0  => "<span class='red'>未还</span>",
				3  => "<span class='yellow'>待审核</span>",
				5  => "<span class='clrc'>初审失败</span>",
				10 => "<span class='green'>等待财务审核</span>",
				15 => "<span class='clrc'>复审失败</span>",
				20 => "<span class='clre'>已还</span>"
			);
			$this->assign('info', $info);
			$this->assign('operate_btn' , $this->getOperateBtn($info['order_state'] , $info['id']));
			$this->assign(array('data_list' => $data_list , 'lxStatusArray'=> $lxStatusArray));
			$this->display();
		}else{
			return $this->index();
		}
	}


	/**
	 * 获取借贷可执行操作
	 */
	public function getOperateBtn($order_state = 0,$orderid = 0){
		$operate_btn = '';
		switch ($order_state) {
			case '10':
				$operate_btn = '<a href="'.U('order/cancel_form',array('id'=>$orderid)).'" class="cancel_btn" rel="pop">取消借贷</a> <a href="javascript:;" onclick="confirmForm('.$orderid.' , 20)" class="return_btn" >确认借贷</a> ';
				break;
			case '30':
				$operate_btn = '<a href="javascript:;" onclick="confirmForm('.$orderid.' , 40)" class="return_btn" >发放借贷</a> ';
				break;
			case '50':
				$operate_btn = '<a href="'.U('order/cancel_payment', array('id' => $orderid)).'" class="cancel_btn" rel="pop">还款失败</a> <a href="javascript:;" onclick="confirmForm('.$orderid.' , 70)" class="return_btn">还款完成</a>';
				break;
			case '62':
				$operate_btn = '<a href="javascript:;" onclick="confirmForm('.$orderid.' , 70)" class="return_btn">还款完成</a>';
				break;		
			default:
				break;
		}
		return $operate_btn;
	}



	public function change_order_status() {
		$orderid = $this->_postid('id');
		$status = $this->_postid('status');
		if(!isHave($orderid) || !isHave($status)) {
			$this->JsonReturn('参数丢失');
		}
		$data = array('order_state' => $status );
		if($status == 70) {
			$data['finish_time'] = TIME;
		}
		$result = M('order')->update($data,array('id'=>$orderid));
		if($result) {
			if($status == 40) { //发放借款，默认插入10期的利息,头期利息默认被扣除
				$rs = D('order')->addInterestRecord($orderid);
				if($rs){
					$this->JsonReturn('ok' , null , 1);
				}else{
					$this->JsonReturn('操作失败');
				}
			}else{
				$this->JsonReturn('ok' , null , 1);
			}
		}else{
			$this->JsonReturn('操作失败');
		}
	}


	public function changeCashStatus() {
		$id = $this->_postid('id');
		$status = $this->_post('status');
		$data ['status'] = $status;
		if($status == 70) {
			//调用微信提现
			T('weixin/weixin.withdraw');
			$withdrawapi = new weixinWithdraw();
			$map['id'] = $id;
			$order_info = M('cash_order')->field("`order_sn`,`openid`,`amount`")->where($map)->find();
			$result = $withdrawapi->send($order_info);
			if($result) {
				$data['finish_time'] = TIME;
				M('cash_order')->update($data , array('id' => $id));
				$this->JsonReturn('ok',null,1);
			}else {
				$this->JsonReturn('提现佣金失败!');
			}
			
		}else{
			M('cash_order')->update($data , array('id' => $id));
			$this->JsonReturn('ok',null,1);
		}
	}

}
